package wxapi

import (
	"encoding/json"
	"fmt"
	"gitee.com/xmcommon/mlog"
	"io/ioutil"
	"net/http"
)

type respGetAccessToken struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
	Errcode     int    `json:"errcode"`
	Errmsg      string `json:"errmsg"`
}

func GetWXAccessToken(appid, appSecret string) (accessToken string, expiresIn int, err error) {
	url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",appid, appSecret)
	request, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	res, err := commonPost(request)
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	var r respGetAccessToken
	err = json.Unmarshal(res, &r)
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	if r.Errcode != 0 {
		err = fmt.Errorf(r.Errmsg)
		mlog.Log.Error(err.Error())
		return
	}
	return r.AccessToken, r.ExpiresIn, nil
}

func commonPost(req *http.Request) (body []byte, err error) {
	client := http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	if resp.StatusCode != 200 {
		err = fmt.Errorf("err request %d", resp.StatusCode)
		mlog.Log.Error(err.Error())
		return
	}
	defer resp.Body.Close()
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		mlog.Log.Error(err.Error())
		return
	}
	return
}
